<template>
  <div>
    <div class="box-shadow pad10 mgb10">
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        class="fnmb talj"
        label-width="70px"
      >
        <div class="flex jbetween">
          <div>
            <el-form-item label="编号">
              <el-input
                v-model="queryParams.Code"
                placeholder="请输入"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="名称">
              <el-input
                v-model="queryParams.Name"
                placeholder="请输入"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="授课形式">
              <el-select
                v-model="queryParams.Mode"
                clearable
                placeholder="请选择"
              >
                <el-option label="理论" value="理论" />
                <el-option label="实操" value="实操" />
              </el-select>
            </el-form-item>
          </div>
          <div class="flex acenter jend fnw">
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <el-row :gutter="10">
      <el-col :span="14">
        <div class="box-shadow pad10">
          <!-- <div class="head-container" style="display: flex">
            <el-button
              type="primary"
              v-hasPermi="['LessonType:add']"
              @click="handleAdd()"
              >添加课程类型</el-button
            >
          </div> -->
          <div class="head-container">
            <el-tree
              :allow-drop="allowDrop"
              :data="classOptions"
              :props="{ label: 'Name', children: 'children', isLeaf: 'isLeaf' }"
              :expand-on-click-node="false"
              ref="treeRef"
              node-key="ID"
              highlight-current
              :load="loadNode"
              lazy
              @node-click="handleNodeClick"
              @node-drop="handleDrop"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span>{{ node.label }}</span>
                  <span v-if="!node.data.ID_Type">
                    <a
                      @click.stop="handleAdd(data)"
                      v-hasPermi="['LessonSystem:add']"
                      style="color: #409eff"
                    >
                      添加课程
                    </a>
                  </span>
                  <span v-else>
                    <span
                      style="color: #e6a23c"
                      v-hasPermi="['LessonSystem:evaluation']"
                      @click="handleEvaluation(data)"
                      >查看评价</span
                    >
                    <el-popconfirm
                      title="确定删除吗？"
                      @confirm="handleDelete(node, data)"
                    >
                      <template #reference>
                        <a
                          style="margin-left: 8px; color: red"
                          v-hasPermi="['LessonSystem:delete']"
                        >
                          删除
                        </a>
                      </template>
                    </el-popconfirm>
                  </span>
                </span>
              </template>
            </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="10">
        <div class="box-shadow pad10" v-show="editInfo.ID">
          <el-form
            :model="editInfo"
            :rules="rules"
            inline
            :label-width="80"
            ref="editFormRef"
            class="wid100"
          >
            <el-form-item label="编号" prop="Code">
              <el-input
                v-model="editInfo.Code"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
            <el-form-item label="名称" prop="Name">
              <el-input
                v-model="editInfo.Name"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
            <el-form-item label="授课形式" prop="Mode">
              <el-select v-model="editInfo.Mode" clearable placeholder="请选择">
                <el-option label="理论" value="理论" />
                <el-option label="实操" value="实操" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="教学设备" prop="ID_Device">
              <Selector
                category="全部设备"
                :query="{ Category: 1 }"
                v-model="editInfo.ID_Device"
              ></Selector>
            </el-form-item> -->
            <el-form-item label="教案文件" prop="LessonPlan">
              <FileUpload
                v-if="editInfo.ID"
                :detail="true"
                v-model:fileList="editInfo.LessonPlanFiles"
              ></FileUpload>
            </el-form-item>
            <el-form-item label="课件文件" prop="Courseware">
              <FileUpload
                v-if="editInfo.ID"
                :detail="true"
                v-model:fileList="editInfo.CoursewareFiles"
              ></FileUpload>
            </el-form-item>
            <div class="flex jcenter">
              <!-- <el-button @click="refresh">刷新页面</el-button> -->

              <el-button
                type="primary"
                size="large"
                v-hasPermi="['LessonSystem:edit']"
                style="width: 100%; border-radius: 6px; margin-bottom: 20px"
                @click="handleEdit"
                >提交修改</el-button
              >
            </div>
          </el-form>
          <div class="subTitle">关联绑定</div>
          <div class="flex jaround acenter">
            <el-button
              type=""
              plain
              size="large"
              style="width: 40%; border-radius: 6px"
              v-hasPermi="['LessonSystem:edit']"
              @click="handleBindUser"
              >授课老师</el-button
            >
            <el-button
              type=""
              size="large"
              plain
              v-hasPermi="['LessonSystem:edit']"
              style="width: 40%; border-radius: 6px"
              @click="handleBindDevice"
              >教学设备</el-button
            >
          </div>
        </div>
        <div v-show="!editInfo.ID" class="flex acenter" style="height: 100%">
          <div>请在左侧选择课程</div>
        </div>
      </el-col>
    </el-row>

    <MyDialog
      v-model:show="show"
      :title="title"
      :width="450"
      :formRef="formRef"
      @confirm="confirm"
      :destroy="true"
    >
      <el-form
        :model="formData"
        :rules="rules"
        inline
        :label-width="80"
        ref="formRef"
        class="wid100"
      >
        <el-form-item label="上级层级">
          {{ currentName }}
        </el-form-item>
        <el-form-item label="编号" prop="Code">
          <el-input v-model="formData.Code" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="名称" prop="Name">
          <el-input v-model="formData.Name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="授课形式" prop="Mode">
          <el-select v-model="formData.Mode" clearable placeholder="请选择">
            <el-option label="理论" value="理论" />
            <el-option label="实操" value="实操" />
          </el-select>
        </el-form-item>
        <el-form-item label="教学设备" prop="ID_Device">
          <Selector
            category="全部设备"
            :query="{ Category: 1 }"
            v-model="formData.ID_Device"
          ></Selector>
        </el-form-item>
        <el-form-item label="教案文件" prop="LessonPlan">
          <FileUpload
            :detail="false"
            v-model:fileList="formData.LessonPlan"
          ></FileUpload>
        </el-form-item>
        <el-form-item label="课件文件" prop="Courseware">
          <FileUpload
            :detail="false"
            v-model:fileList="formData.Courseware"
          ></FileUpload>
        </el-form-item>
      </el-form>
    </MyDialog>
    <!-- 绑定用户 -->
    <MyDialog
      v-model:show="showBindUser"
      :title="title"
      @confirm="submitBindUser"
      :destroy="true"
    >
      <UserTable
        :userColumns="userColumns"
        v-model:checkList="bindData"
        :query="{ Type: 2 }"
        :Type="true"
        :showAdd="false"
      ></UserTable>
    </MyDialog>
    <!-- 绑定设备 -->
    <MyDialog
      v-model:show="showBindDevice"
      :title="title"
      @confirm="submitBindDevice"
      :destroy="true"
    >
      <DeviceTable
        v-model:checkList="bindDeviceData"
        :deviceColumns="deviceColumns"
      ></DeviceTable>
    </MyDialog>

    <MyDialog
      v-model:show="showEvaluation"
      :title="title"
      :showFooter="false"
      :width="1000"
    >
      <MyTable
        :tableList="EvaluationList"
        v-model:page="page2"
        :total="Total2"
        :toolbar="false"
        :columns="columns2"
      ></MyTable>
    </MyDialog>
  </div>
</template>

<script setup name="LessonSystem">
import UserTable from '@/views/system/User/index';
import DeviceTable from '@/views/teachingDevice/DeviceAccount/index';
import { getCurrentInstance, onMounted, ref, watch } from 'vue';
import { GetCourseTypeList_Page } from '@/api/lesson/lessonType.js';
import { GetCourseEvalDetailList_Page } from '@/api/attendance/evaluation.js';
import {
  GetCourseList_Page,
  AddCourse,
  EditCourse,
  DelCourse,
  GetCourseDetail,
  CourseBindTeacher,
  CourseBindDevice
} from '@/api/lesson/lessonSystem.js';
const { proxy } = getCurrentInstance();
const className = ref('');

const classOptions = ref([]);
const editInfo = ref({});
const show = ref(false);
const title = ref('');
const userColumns = ref([
  { label: '多选框' },
  { label: '序号' },
  { label: '用户名称', prop: 'Name' },
  { label: '状态', tag: true, prop: 'tags' },
  { label: '电话号码', prop: 'Phone' },
  { label: '备注', prop: 'Remark', width: 300, input: true }
]);
const Total2 = ref(0);
const columns2 = ref([
  { label: '序号' },
  { label: '评分', prop: 'Score', rate: true, disabled: true },
  { label: '评语', prop: 'Comment' },
  { label: '班级', prop: 'Name_Class' },
  { label: '教师', prop: 'Name_Teacher' },
  { label: '创建时间', prop: 'CreateTime', width: 170 },
  { label: '创建人', prop: 'CreateUser', user: true }
]);
const deviceColumns = ref([
  { label: '多选框' },
  { label: '序号' },
  { label: '编号', prop: 'Code', link: true, self: true },
  { label: '名称', prop: 'Name' },
  { label: '图片', prop: 'ShowPictrue', img: true },
  { label: '区域', prop: 'Area' },
  { label: '场地', prop: 'Place' },
  { label: '规格型号', prop: 'Model' },
  { label: '状况', tag: true, prop: 'State_SelfName' },
  { label: '过程状态', tag: true, prop: 'StateName' },
  { label: '类型', prop: 'Type' },
  { label: '应用范围', prop: 'Place' }
  // { label: '操作', width: 200 }
]);
proxy.$formatKey(deviceColumns.value);
proxy.$formatKey(columns2.value);
const rules = ref({
  Code: [{ required: true, message: '请输入', trigger: 'blur' }],
  Name: [{ required: true, message: '请输入', trigger: 'blur' }],
  Principal: [{ required: true, message: '请选择', trigger: 'blur' }],
  Mode: [{ required: true, message: '请选择', trigger: 'blur' }]
});
const formData = ref({
  LessonPlan: [],
  Courseware: []
});
const formRef = ref();
const showEvaluation = ref(false);
const EvaluationList = ref([]);
const treeRef = ref();
const currentName = ref();
const subID = ref();
const editFormRef = ref();
const page = ref({
  PageIndex: 1,
  PageSize: 10
});
const page2 = ref({
  PageIndex: 1,
  PageSize: 10
});
const queryParams = ref({
  Code: '',
  Name: '',
  Type: '',
  Device: '', //设备ID
  Mode: '', //授课形式：理论，实操
  NoPage: 'true'
});
const showBindUser = ref(false);
const originSelected = ref([]);
const bindData = ref([]);
const bindDeviceData = ref([]);
const showBindDevice = ref(false);
watch(className, val => {
  treeRef.value?.filter(val);
});

onMounted(() => {
  //   getList();
});
async function getList() {
  show.value = false;
  try {
    let query = {
      ...queryParams.value,
      ...page.value
    };
    let res = await GetCourseList_Page(query);
    res.data?.forEach(item => {
      item.isLeaf = true;
    });
    classOptions.value = res.data;
  } catch (error) {
    console.log(error);
  }
}

//绑定设备
function handleBindDevice() {
  title.value = '绑定教学设备';
  editInfo.value.BindDevices?.forEach(item => (item.ID = item.ID_Device));
  bindDeviceData.value = editInfo.value.BindDevices;
  showBindDevice.value = true;
}

async function submitBindDevice() {
  try {
    let query = {
      ID_Course: editInfo.value.ID,
      Devices: bindDeviceData.value?.map(item => {
        return {
          ID_Device: item.ID,
          Code: item.Code,
          Name: item.Name
        };
      })
    };
    await CourseBindDevice(query);
    await handleNodeClick({
      ID_Type: editInfo.value.ID_Type,
      ID: editInfo.value.ID
    });
    proxy.$modal.msgSuccess('绑定设备成功');
    showBindDevice.value = false;
  } catch (error) {
    console.log(error);
  }
}

async function handleEvaluation(data) {
  try {
    let query = {
      ...page2.value,
      CourseID: data.ID,
      NoPage: ''
    };
    let res = await GetCourseEvalDetailList_Page(query);
    EvaluationList.value = res.data.List;
    Total2.value = res.data.Total;
    title.value = '课程评价';
    showEvaluation.value = true;
  } catch (error) {
    console.log(error);
  }
}

async function handleQuery() {
  // try {
  //   let res = await GetCourseTypeList_Page();
  //   classOptions.value = res.data;
  // } catch (error) {
  //   console.log(error);
  // }
  getList();
}

async function submitBindUser() {
  try {
    let query = {
      ID_Course: editInfo.value.ID,
      Teachers: bindData.value?.map(item => {
        return {
          ID_User: item.ID,
          Remark: item.Remark
        };
      })
    };
    await CourseBindTeacher(query);
    await handleNodeClick({
      ID_Type: editInfo.value.ID_Type,
      ID: editInfo.value.ID
    });
    proxy.$modal.msgSuccess('绑定成功');
    showBindUser.value = false;
  } catch (error) {
    console.log(error);
  }
}

async function confirm() {
  try {
    formRef.value.validate(async valid => {
      if (valid) {
        let query = {
          ...formData.value,
          //   Pid: subID.value,
          LessonPlan: formData.value.LessonPlan?.map(item => {
            return { FileID: item.ID, Sort: item.Sort };
          }),
          Courseware: formData.value.Courseware?.map(item => {
            return { FileID: item.ID, Sort: item.Sort };
          })
        };

        await AddCourse(query);
        proxy.$modal.msgSuccess('添加成功');
        // if (subID.value != 0) {
        let node = treeRef.value.getNode(formData.value.ID_Type);
        node.loaded = false;
        node.loadData();
        node.loaded = true;
        // } else {
        //   treeRef.value.append({ ...query, ID: res.data, isLeaf: true });
        // }
        show.value = false;
        // getList();
      }
    });
  } catch (error) {
    console.log(error);
  }
}

async function handleDelete(node, data) {
  try {
    await DelCourse({ ID: data.ID });
    proxy.$modal.msgSuccess('删除成功');
    treeRef.value.remove(node);
    if (data.ID == editInfo.value.ID) {
      editInfo.value = {};
    }
    show.value = false;
    // getList();
  } catch (error) {
    console.log(error);
  }
}

function allowDrop(draggingNode, dropNode, DropType) {
  if (
    draggingNode.data.ID_Type &&
    DropType == 'inner' &&
    !dropNode.data.ID_Type
  ) {
    return true;
  }
  //   console.log(draggingNode, dropNode);
  //   return DropType == "inner";
}

async function handleDrop(draggingNode, dropNode, dropType) {
  let res = await GetCourseDetail({ ID: draggingNode.data.ID });
  try {
    let Info = res.data.Info;
    let query = {
      ...Info,
      ID_Type: dropNode.data.ID,
      LessonPlan: Info.LessonPlanFiles?.map(item => {
        return {
          FileID: item.FileID,
          Sort: item.Sort
        };
      }),
      Courseware: Info.CoursewareFiles?.map(item => {
        return {
          FileID: item.FileID,
          Sort: item.Sort
        };
      })
    };
    await EditCourse(query);
    proxy.$modal.msgSuccess('修改成功');
    // let node = treeRef.value.getNode(draggingNode.data.ID);
    // node.loaded = false;
    // node.loadData();
    // node.loaded = true;
    treeRef.value.append(draggingNode, dropNode.data.ID);
    // resetQuery();
    // getList();
  } catch (error) {
    getList();
    console.log(error);
  }
}

async function loadNode(node, resolve) {
  try {
    let res;
    if (node.level == 0) {
      resetQuery();
    } else {
      console.log(node);
      let query = {
        ...queryParams.value,
        Type: node.data?.ID
      };
      res = await GetCourseList_Page(query);
    }
    if (!res) return;
    let list = res.data?.map(item => {
      return {
        ...item,
        isLeaf: true
      };
    });
    resolve(list);
  } catch (error) {
    console.log(error);
  }
}

function handleBindUser() {
  if (!editInfo.value.ID) return proxy.$modal.msgError('请先选择课程');
  title.value = '绑定课程老师';

  editInfo.value.BindTeachers?.forEach(item => (item.ID = item.ID_User));
  bindData.value = editInfo.value.BindTeachers;
  showBindUser.value = true;
}

function handleEdit() {
  if (!editInfo.value.ID) return proxy.$modal.msgError('请先选择课程');
  editFormRef.value.validate(async valid => {
    if (valid) {
      try {
        let query = {
          ...editInfo.value,
          LessonPlan: editInfo.value.LessonPlanFiles?.map(item => {
            return {
              FileID: item.FileID,
              Sort: item.Sort
            };
          }),
          Courseware: editInfo.value.CoursewareFiles?.map(item => {
            return {
              FileID: item.FileID,
              Sort: item.Sort
            };
          })
        };
        await EditCourse(query);
        // let node = treeRef.value.getNode(query.ID);
        // node.data = query;
        proxy.$modal.msgSuccess('修改成功');
      } catch (error) {
        console.log(error);
      }
    }
  });
}

function handleAdd(row) {
  console.log(row);
  formData.value = {
    LessonPlan: [],
    Courseware: []
  };
  show.value = true;
  if (row) {
    title.value = '添加课程';
    currentName.value = row.Name;
    // subID.value = row.ID;
    formData.value.ID_Type = row.ID;
  } else {
    // subID.value = "0";
    title.value = '添加根级';
  }
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.Name.indexOf(value) !== -1;
};
async function handleNodeClick(val) {
  if (val.ID_Type) {
    let res = await GetCourseDetail({ ID: val.ID });
    editInfo.value = {
      ...res.data.Info,
      BindTeachers: res.data.BindTeachers,
      BindDevices: res.data.BindDevices
    };
  } else {
    editInfo.value = {};
  }
}
async function resetQuery() {
  queryParams.value = {
    Code: '',
    Name: '',
    Type: '', //类型 1:学年 2:院系 3:专业 4:班级
    Device: '', //设备ID
    Mode: '', //授课形式：理论，实操
    Device: '',
    NoPage: 'true'
  };
  editInfo.value = {};
  try {
    let query = {
      Code: '',
      Name: '',
      NoPage: 'true'
    };
    let res = await GetCourseTypeList_Page(query);
    res.data?.forEach(item => {
      item.isLeaf = !item.HasChild;
    });
    classOptions.value = res.data;
  } catch (error) {
    console.log(error);
  }
  //   getList();
}
</script>

<style lang="scss" scoped>
.subTitle {
  padding: 0 0 10px 10px;
  font-weight: bold;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
